/**
 * 文件名：FileUtils.java
 *
 * 版本信息：v1.0
 * 日期：2013-6-21
 * Copyright  Corporation 2013 
 * 版权所有
 *
 */

package com.foreveross.bsl.common.utils.bean;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.json.JSONObject;

/**
 * 此类描述的是：文件操作工具类
 * 
 * @author: panhm@foreveross.com
 * @version: 2013-6-21 上午10:09:57
 */

public class FileUtils {

	/**
	 * dirPath:TODO 文件保存路径
	 * 
	 * @since Ver 1.1
	 */

	public static String dirPath = "/tmp/cube-server/files";

	/**
	 * 此方法描述的是：生成文件，并且返回文件所在本地磁盘的相对路径
	 * 
	 * @param dirName
	 *            目录名称
	 * @param fileName
	 *            文件名称
	 * @param fileBytes
	 *            文件字节数据
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-21 上午10:17:29
	 */

	public static String saveFile(File destFile, byte[] fileBytes)
			throws IOException {
		// String dirPathName = dirPath + File.separator + dirName;
		if (!destFile.getParentFile().exists()) {
			destFile.getParentFile().mkdirs();
		}
		// String uuid = UUID.randomUUID().toString();
		// String localFilename = dirName + File.separator + uuid + "_" +
		// fileName;
		// File destFile = new File(dirPath + File.separator + localFilename);
		OutputStream o = null;
		DataOutputStream dos = null;
		try {
			o = new FileOutputStream(destFile);
			dos = new DataOutputStream(o);
			dos.write(fileBytes);
			dos.flush();
			return destFile.getName();
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				if (dos != null)
					dos.close();
				if (o != null)
					o.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * 此方法描述的是：读取文件
	 * 
	 * @param localFilename
	 *            本地文件的相对路径名称
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-19 下午4:58:00
	 * @throws IOException
	 */

	public static byte[] readFile(File destFile) throws IOException {
		// File destFile = new File(localFileName);
		FileInputStream in = null;
		DataInputStream dos = null;
		try {
			// added by Heyaowen
			if(!destFile.exists())
				throw new IOException("文件" + destFile.getName() + "不存在！");
			in = new FileInputStream(destFile);
			int size = in.available();
			byte[] buff = new byte[size];
			dos = new DataInputStream(in);
			dos.read(buff);
			return buff;
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				if (dos != null)
					dos.close();
				if (in != null)
					in.close();
			} catch (IOException e1) {
				throw e1;
			}
		}
	}

	/**
	 * 此方法描述的是：读取zip包图片文件信息
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-25 上午10:29:20
	 * @throws Exception
	 */

	public static byte[] readPngFile(File file, String entryname) throws Exception {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		InputStream in = null;
		try {
			// added by Heyaowen
			if (!file.exists())
				throw new Exception("文件" + file.getName() + "不存在！");
			ZipFile zip = new ZipFile(file);
			ZipEntry ze = zip.getEntry(entryname);// 根据文件名取得压缩包中的对应条目
			in = zip.getInputStream(ze);
			int index = 0;
			while ((index = in.read()) != -1) {
				outputStream.write(index);
			}
			byte data[] = outputStream.toByteArray();
			outputStream.flush();
			return data;
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				if (outputStream != null)
					outputStream.close();
				if (in != null)
					in.close();
			} catch (IOException e1) {
				throw e1;
			}
		}
	}

	/**
	 * 此方法描述的是：读取zip包配置文件信息
	 * 
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-25 上午10:29:20
	 * @throws Exception
	 */

	public static String readZipConfig(File file, String entryname)
			throws Exception {
		InputStream in = null;
		BufferedReader bufRead = null;
		try {
			ZipFile zip = new ZipFile(file);
			ZipEntry ze = zip.getEntry(entryname);// 根据文件名取得压缩包中的对应条目
			in = zip.getInputStream(ze);
			bufRead = new BufferedReader(new InputStreamReader(in, "utf-8"));
			String str = null;
			StringBuffer sb = new StringBuffer();
			while ((str = bufRead.readLine()) != null) {
				sb.append(str);
			}
			String stringJson = sb.toString().replaceAll("\\s", "");
			if (stringJson.length() > 0) {
				stringJson = stringJson.substring(stringJson.indexOf("{"));
			}
			return stringJson;
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * 此方法描述的是：修改某个文件信息
	 * 
	 * @param fileName
	 *            文件名称
	 * @param fileBytes
	 *            信息字节
	 * @author: panhm@foreveross.com
	 * @version: 2013-6-28 下午5:48:50
	 * @throws Exception
	 */

	public static void modifyFile(File file, byte[] fileBytes) throws Exception {
		// File file = new File(dirPath + File.separator + fileName);
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			fos.write(fileBytes);
			fos.flush();
		} catch (Exception e) {
			throw e;
		} finally {
			if (fos != null) {
				try {
					fos.close();
					fos = null;
				} catch (IOException e) {
					fos = null;
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 修改模块配置文件内容
	 * 
	 * @param fileName
	 * @param json
	 * @throws Exception
	 */
	public static String modifyConfigFile(String fileName, Map<String, Object> json) throws Exception {
		String file = dirPath + File.separator + fileName;
		File zipFile = new File(file);
		String tempPath = ZipUtils.unzip(zipFile); // zip
		String configFilePath = tempPath + File.separator + "CubeModule.json";
		File configFile = new File(configFilePath);
		// added by heyaowen adapter package and 优化逻辑
		if(!configFile.exists())
			configFile = new File(tempPath + File.separator + "package.json");
		byte[] fileBytes = FileUtils.readFile(configFile);
		String stringJson = new String(fileBytes, "utf-8");
		stringJson = stringJson.replaceAll("\\s", "");
		if (stringJson.length() > 0) {
			stringJson = stringJson.substring(stringJson.indexOf("{"));
		}
		// TODO 统一JSON工具用Jackson added by Wangyi
		JSONObject jsonConfig = new JSONObject(stringJson);
		JSONObject jBody = new JSONObject(json);
		if (jBody != null) {
			Iterator iterator = jBody.keys();
			while (iterator.hasNext()) {
				String key = (String) iterator.next();
				jsonConfig.put(key, jBody.get(key));
			}
		}
		FileUtils.modifyFile(configFile, jsonConfig.toString().getBytes("utf-8"));

		File desczipfile = new File(file);
		ZipUtils.zipFile(desczipfile, tempPath);
		ZipUtils.del(tempPath);
		return file;
	}

}
